package com.sns.sina;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.sns.sina.AsyncWeiboRunner.RequestListener;
import com.yibudong.found.R;

public class SinaOauth2Activity extends Activity{
	private static final String TAG = SinaOauth2Activity.class.getSimpleName();
	
	private Weibo mWeibo = Weibo.getInstance();
	
    private WebView mWebView;
    
    private ProgressBar mProgressBar;
    
    private WeiboDialogListener mListener = new AuthDialogListener();
    
    private String mUrl;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.sina_oauth2);
		mProgressBar = (ProgressBar)findViewById(R.id.progress_for_webview);
		mProgressBar.setProgress(0);
		setUpWebView();
	}
	
    private void setUpWebView() {
        mWebView = (WebView)findViewById(com.yibudong.found.R.id.webview_sina_oauth2);
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new WeiboWebViewClient());
        mWebView.setWebChromeClient(new WebChromeClient(){

			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				super.onProgressChanged(view, newProgress);
				mProgressBar.setProgress(newProgress);
			}
        	
        });
        mUrl = mWeibo.makeOauthURL(this);
        if(!TextUtils.isEmpty(mUrl)){
            mWebView.loadUrl(mUrl);
        }else{
        	Log.e(TAG, "makeURL() return " + mUrl);
        	setResult(RESULT_CANCELED);
        	finish();
        }
    }
    
    private void handleRedirectUrl(WebView view, String url) {
        Bundle values = Utility.parseUrl(url);

        String error = values.getString("error");
        String error_code = values.getString("error_code");

        if (error == null && error_code == null) {
            mListener.onComplete(values);
        } else if (error.equals("access_denied")) {
            // 用户或授权服务器拒绝授予数据访问权限
            mListener.onCancel();
        } else {
            mListener.onWeiboException(new WeiboException(error, Integer.parseInt(error_code)));
        }
    }
    
    private class WeiboWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG, "Redirect URL: " + url);
            // 待后台增加对默认重定向地址的支持后修改下面的逻辑
            if (url.startsWith(mWeibo.getRedirectUrl())) {
                handleRedirectUrl(view, url);
                
                return true;
            }
            // launch non-dialog URLs in a full browser
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description,
                String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            mListener.onError(new DialogError(description, errorCode, failingUrl));
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d(TAG, "onPageStarted URL: " + url);
            // google issue. shouldOverrideUrlLoading not executed
            if (url.startsWith(mWeibo.getRedirectUrl())) {
                handleRedirectUrl(view, url);
                view.stopLoading();
                return;
            }
            mProgressBar.setVisibility(View.VISIBLE);
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            Log.d(TAG, "onPageFinished URL: " + url);
            super.onPageFinished(view, url);
            mProgressBar.setVisibility(View.GONE);
        }

        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

    }
    
	private static final String CONSUMER_SECRET = "029fa9aeec2482069f03a49ddb9572df";// 鏇挎崲涓哄紑鍙戣�鐨刟ppkey锛屼緥濡�94098772160b6f8ffc1315374d8861f9";
    
	class AuthDialogListener implements WeiboDialogListener {

		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			String uid = values.getString("uid");
			String text = "access_token : " + token + "  expires_in: "
					+ expires_in + "|uid:" + uid;
			
            // ensure any cookies set by the dialog are saved
            CookieSyncManager.getInstance().sync();
			AccessToken accessToken = new AccessToken(token, Weibo.APP_SECRET);
			accessToken.setExpiresIn(expires_in);
			Weibo.getInstance().setAccessToken(accessToken);

			Log.i(TAG, text);
			
			Toast.makeText(SinaOauth2Activity.this, "认证成功", Toast.LENGTH_SHORT).show();
			
			mWebView.setVisibility(View.INVISIBLE);
			
			Intent intent = new Intent();
			intent.putExtra("uid", uid);
			setResult(RESULT_OK, intent);
			SinaOauth2Activity.this.finish();
		}

		@Override
		public void onError(DialogError e) {
			Toast.makeText(getApplicationContext(),
					"Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
		}

		@Override
		public void onCancel() {
			Toast.makeText(getApplicationContext(), "Auth cancel",
					Toast.LENGTH_LONG).show();
		}

		@Override
		public void onWeiboException(WeiboException e) {
			Toast.makeText(getApplicationContext(),
					"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
					.show();
		}

	}
	
	private RequestListener mRequestListener = new RequestListener(){

		@Override
		public void onComplete(String response) {
			try {
				JSONObject jObj = new JSONObject(response);
				if(jObj.has("uid")){
					String uid = jObj.getString("uid");
					Intent intent = new Intent();
					intent.putExtra("uid", uid);
					intent.putExtra("accessToken", mWeibo.getAccessToken().getToken());
					setResult(RESULT_OK, intent);
					Log.i(TAG, "uid:" + uid);
				}else{
					setResult(RESULT_CANCELED);
				}
				finish();
			} catch (JSONException e) {
				Log.e(TAG, "getUID has a error," + e);
				setResult(RESULT_CANCELED);
				finish();
			} 
		}

		@Override
		public void onIOException(IOException e) {
			Log.e(TAG, "getUid has a Exception:" + e);
			setResult(RESULT_CANCELED);
			finish();
		}

		@Override
		public void onError(WeiboException e) {
			Log.e(TAG, "getUid has a error:" + e + "|errorcode:" + e.getStatusCode());
			setResult(RESULT_CANCELED);
			finish();
		}};
	
}
